package com.trigsoft.applist;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.util.Log;

import com.trigsoft.utils.CatGetter;

public class AppReceiver extends BroadcastReceiver
{
	private class UpdateTask implements Runnable
	{

		public void run()
		{
			// TODO Auto-generated method stub
			PackageManager pkgMgt = context.getPackageManager();

			Log.d("Applist", action);
			List<String> names = new ArrayList<String>();
			DBHelper.init(context);
			if (Intent.ACTION_PACKAGE_ADDED.equals(action))
			{
				final List<ResolveInfo> matches = findActivitiesForPackage(context, pkg);

				if (matches.size() > 0)
				{
					for (ResolveInfo info : matches)
					{
						Bitmap b = ((BitmapDrawable) (info.loadIcon(pkgMgt))).getBitmap();
						String n = info.activityInfo.name;
						String p = info.activityInfo.packageName;
						String l = info.loadLabel(pkgMgt).toString();
						String pinyin = PinyinTransformer.getPingYinInitial(l);
						names.add(n);
						String dn;
						try
						{
							dn = pkgMgt.getApplicationInfo(pkg, 0).loadLabel(pkgMgt).toString();
						} catch (NameNotFoundException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
							dn = "";
						}
						int d = dn.compareTo(l) == 0 ? App.YES : App.NO;
						if (replacing)
							IconCache.icons.remove(l);
						IconCache.icons.put(l, b);
						DBHelper.createOrUpdate(new App(b, n, p, pinyin, l, d));
						DBHelper.attachCat(context);
						DBHelper.updateCat(new CatGetter(context).getCat(pkg, true), pkg);
						DBHelper.detachCat();
					}
				}
				if (replacing)
				{
					Cursor cur = DBHelper.queryByPKG(pkg);
					if (cur.getCount() != names.size())
					{
						while (cur.moveToNext())
						{
							String cls = cur.getString(cur.getColumnIndex(DBHelper.KEY_NAME));
							if (!names.contains(cls))
							{
								/* As label can be same for different activities in different version, 
								 * remove icon in cache is not safe.
								 */
								DBHelper.deleteAppEntryByName(cls);
							}
						}
					}
				}
			} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && !replacing)
			/* Remove when uninstallation */
			{
				Cursor cur = DBHelper.queryByPKG(pkg);

				while (cur.moveToNext())
				{
					IconCache.icons.remove(cur.getString(cur.getColumnIndex(DBHelper.KEY_LABEL)));
				}

				DBHelper.deleteAppEntry(pkg);
			}

			DBHelper.close();
		}

	}

	/** From Launcher2 --- Android Source
	 * Query the package manager for MAIN/LAUNCHER activities in the supplied package.
	 */
	private static List<ResolveInfo> findActivitiesForPackage(Context context, String packageName)
	{
		final PackageManager packageManager = context.getPackageManager();

		final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		mainIntent.setPackage(packageName);

		final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
		return apps != null ? apps : new ArrayList<ResolveInfo>();
	}

	Context context;
	boolean replacing;

	String action;

	String pkg;

	String getPackageName(Intent intent)
	{
		Uri uri = intent.getData();
		String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
		return pkg;
	}

	@SuppressWarnings("static-access")
	@Override
	public void onReceive(Context context, Intent intent)
	{
		// TODO Auto-generated method stub
		this.context = context;

		action = intent.getAction();
		replacing = intent.getBooleanExtra(intent.EXTRA_REPLACING, false);

		pkg = getPackageName(intent);
		//int uid = intent.getIntExtra(Intent.EXTRA_UID, 0);
		//int flag = intent.getFlags();
		new Thread(new UpdateTask()).run();
	}
}
